<template>
  <div :id="tableName + '_form'">
    <div
      v-if="!!formData.id && !!onlineExtConfigJson.reportPrintShow"
      style="text-align: right; position: absolute; top: 15px; right: 20px; z-index: 999"
    >
      <PrinterOutlined title="打印" @click="onOpenReportPrint" style="font-size: 16px" />
    </div>
    <detail-form :schemas="detailFormSchemas" :data="formData" :span="formSpan" />
    <a-tabs v-if="hasSubTable && showSub">
      <template #default>
        <template v-for="(sub, index) in subTabInfo" :key="index">
          <a-tab-pane :tab="sub.describe" :forceRender="true">
            <div v-if="sub.relationType == 1" :style="{ 'overflow-y': 'auto', 'overflow-x': 'hidden', 'max-height': subFormHeight + 'px' }">
              <online-sub-form-detail
                :table="sub.key"
                :form-template="formTemplate"
                :main-id="getSubTableForeignKeyValue(sub.foreignKey)"
                :properties="sub.properties"
              />
            </div>
            <div v-else>
              <JVxeTable
                :ref_for="true"
                :ref="refMap[sub.key]"
                toolbar
                keep-source
                row-number
                row-selection
                :height="subTableHeight"
                :disabled="true"
                :columns="sub.columns"
                :dataSource="subDataSource[sub.key]"
                @authPre="getSubTableAuthPre(sub.key)"
              />
            </div>
          </a-tab-pane>
        </template>
      </template>
    </a-tabs>
    <Loading :loading="loading" :absolute="false" />
    <slot name="bottom"></slot>
  </div>
</template>
<script lang="ts">
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ref, reactive, defineComponent } from 'vue';
  import { Loading } from '/@/components/Loading';
  import { getToken } from '/@/utils/auth';
  import { goJmReportViewPage } from '/@/utils';
  import { PrinterOutlined } from '@ant-design/icons-vue';
  import DetailForm from '../../extend/form/DetailForm.vue';
  import OnlineSubFormDetail from './OnlineSubFormDetail.vue';
  import { getDetailFormSchemas } from '../../use/useAutoForm';
  import { defHttp } from '/@/utils/http/axios';

  export default defineComponent({
    name: 'OnlineFormDetail',
    components: {
      DetailForm,
      Loading,
      PrinterOutlined,
      OnlineSubFormDetail,
    },
    props: {
      id: {
        type: String,
        default: '',
      },
      formTemplate: {
        type: Number,
        default: 1,
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      isTree: {
        type: Boolean,
        default: false,
      },
      pidField: {
        type: String,
        default: '',
      },
      submitTip: {
        type: Boolean,
        default: true,
      },
      showSub: {
        type: Boolean,
        default: true,
      },
    },
    emits: ['success', 'rendered'],
    setup(props, { emit }) {
      console.log('onlineForm-setup》》');
      const { createMessage: $message } = useMessage();
      const tableName = ref('');
      const single = ref(true);
      const loading = ref(false);
      const tableType = ref(1);
      const formData = ref({});
      const subFormHeight = ref(300);
      const subTableHeight = ref(340);
      const onlineExtConfigJson = reactive({
        reportPrintShow: 0,
        reportPrintUrl: '',
        joinQuery: 0,
        modelFullscreen: 0,
        modalMinWidth: '',
      });
      const { detailFormSchemas, hasSubTable, subTabInfo, refMap, subDataSource, createFormSchemas, formSpan } = getDetailFormSchemas(props);
      function handleExtConfigJson(jsonStr) {
        let extConfigJson = { reportPrintShow: 0, reportPrintUrl: '', joinQuery: 0, modelFullscreen: 1, modalMinWidth: '' };
        if (jsonStr) {
          extConfigJson = JSON.parse(jsonStr);
        }
        Object.keys(extConfigJson).map((k) => {
          onlineExtConfigJson[k] = extConfigJson[k];
        });
      }
      async function createRootProperties(data) {
        tableType.value = data.head.tableType;
        tableName.value = data.head.tableName;
        single.value = data.head.tableType == 1;
        handleExtConfigJson(data.head.extConfigJson);
        createFormSchemas(data.schema.properties);
        emit('rendered', onlineExtConfigJson);
      }
      async function show(_status, record) {
        console.log('进入表单详情》》form', record);
        await edit(record);
      }
      function getFormData(dataId) {
        let url = `/api-online/online/cgform/api/detail/${props.id}/${dataId}`;
        return new Promise((resolve, reject) => {
          defHttp
            .get({ url }, { isTransformResponse: false })
            .then((res) => {
              if (res.success) {
                resolve(res.data);
              } else {
                reject();
                $message.warning(res.message);
              }
            })
            .catch(() => {
              reject();
            });
        });
      }
      async function edit(record) {
        let temp = await getFormData(record.id);
        formData.value = Object.assign({}, temp);
        editSubVxeTableData(temp);
      }
      function editSubVxeTableData(record) {
        if (!record) {
          record = {};
        }
        let keys = Object.keys(subDataSource.value);
        if (keys && keys.length > 0) {
          let obj = {};
          for (let key of keys) {
            obj[key] = record[key] || [];
          }
          subDataSource.value = obj;
        }
      }
      function getSubTableAuthPre(table) {
        return 'online_' + table + ':';
      }
      function onOpenReportPrint() {
        let url = onlineExtConfigJson.reportPrintUrl;
        let temp = formData.value;
        if (temp) {
          let id = temp.id;
          let token = getToken();
          goJmReportViewPage(url, id, token);
        }
      }
      function getSubTableForeignKeyValue(key) {
        let temp = formData.value;
        console.log('getValueIgnoreCase(temp, key)', temp, key, getValueIgnoreCase(temp, key));
        return getValueIgnoreCase(temp, key);
      }
      function getValueIgnoreCase(data, key) {
        if (data) {
          let temp = data[key];
          if (!temp && temp !== 0) {
            temp = data[key.toLowerCase()];
            if (!temp && temp !== 0) {
              temp = data[key.toUpperCase()];
            }
          }
          return temp;
        }
        return '';
      }
      return {
        detailFormSchemas,
        formData,
        formSpan,
        tableName,
        loading,
        hasSubTable,
        subTabInfo,
        subFormHeight,
        subTableHeight,
        refMap,
        subDataSource,
        getSubTableAuthPre,
        show,
        createRootProperties,
        onOpenReportPrint,
        onlineExtConfigJson,
        getSubTableForeignKeyValue,
      };
    },
  });
</script>
<style scoped></style>
